package arm.attestation.bean;

import arm.common.manager.TableManager;
import arm.attestation.entity.Contract;
import arm.attestation.entity.Obiekt;
import arm.db.tools.DBManager;
import arm.dic.entity.DicPeriod;

import javax.faces.model.SelectItem;
import java.util.ArrayList;
import java.util.List;

public class ObiektBean
{

    private Obiekt obiekt;
    private TableManager<Obiekt> tableManager;
    private ReportBean reportBean;


    public Obiekt getObiekt()
    {
        return obiekt;
    }

    public void setObiekt(Obiekt obiekt)
    {
        this.obiekt = obiekt;
    }

    public String viewTable ()
    {
        getTableManager().readFromDB();
        return "viewObiektTable" ;
    }

    public TableManager<Obiekt> getTableManager ()
    {
        if (tableManager==null)
        {
            tableManager=new TableManager<Obiekt>(Obiekt.class);
        }
        return tableManager;
    }

    public void setTableManager (TableManager<Obiekt> tableManager)
    {
        this.tableManager=tableManager;
    }

    public String create()
    {
        obiekt = new Obiekt();
        return "editObiekt";
    }

    public String save()
    {
        DBManager.saveOrUpdate(getObiekt());
        return viewTable();
    }

    public String edit () {
        setObiekt(getTableManager().getSelectedObj());
        return "editObiekt";
    }

    public String createReport ()
    {
        setObiekt(getTableManager().getSelectedObj());
        return getReportBean().toPage();
    }

    public  String cancel ()
    {
        return viewTable();
    }

    public void delete ()
    {
        DBManager.delete(getTableManager().getSelectedObj());
        getTableManager().readFromDB();
    }

    public List<SelectItem> getPeriodList()
    {
        List<DicPeriod> objs = DBManager.readList(DicPeriod.class.getName());
        List<SelectItem> selectItems = new ArrayList();
        for (DicPeriod obj : objs)
        {
            selectItems.add(new SelectItem(obj, obj.getName()));
        }
        return selectItems;

    }

    public List<SelectItem> getContractList()
    {
        List<Contract> objs = DBManager.readList(Contract.class.getName());
        List<SelectItem> selectItems = new ArrayList();
        for (Contract obj : objs)
        {
            selectItems.add(new SelectItem(obj, obj.getNum().toString()));
        }
        return selectItems;
    }

    public ReportBean getReportBean() {
        if (reportBean == null)
        {
            reportBean = new ReportBean(this);
        }
        return reportBean;
    }
}